#include "MouseController.h"
#define BUFFER_SIZE		16

bool MouseController::initialize() {
	if FAILED( InputDevice::getDirectInput()->CreateDevice(GUID_SysMouse, &dMouse, NULL) ) {
		return false;
	} else {
		HRESULT hr;

		hr = dMouse->SetDataFormat( &c_dfDIMouse );
		if ( FAILED(hr) ) 
			return false;

		hr = dMouse->SetCooperativeLevel( InputController::getHWnd(), 
			DISCL_EXCLUSIVE  | DISCL_FOREGROUND);

		if ( FAILED(hr) ) 
			return false;


		// setup the buffer size for the mouse data
		DIPROPDWORD dipdw;

		dipdw.diph.dwSize = sizeof(DIPROPDWORD);
		dipdw.diph.dwHeaderSize = sizeof(DIPROPHEADER);
		dipdw.diph.dwObj = 0;
		dipdw.diph.dwHow = DIPH_DEVICE;
		dipdw.dwData = BUFFER_SIZE;

		hr = dMouse->SetProperty( DIPROP_BUFFERSIZE, &dipdw.diph );
		if ( FAILED(hr) ) 
			return false;

		return true;
	}


}
bool MouseController::terminate() {
	dMouse->Unacquire();
	return true;
}

void MouseController::unAcquire() {
	dMouse->Unacquire();
}

MouseController::MouseController() {
	dMouse=NULL;
	x=0;
	y=0;
}

HRESULT MouseController::acquire() {
	return dMouse->Acquire();
}

void MouseController::poll() {

	BOOL                bDone;
    DIDEVICEOBJECTDATA  od;
    DWORD               dwElements;
    HRESULT             hr;

	
	bDone = FALSE;

    while ( !bDone ) {
        dwElements = 1;
        hr = dMouse->GetDeviceData( 
                            sizeof(DIDEVICEOBJECTDATA), 
                            &od,
                            &dwElements, 
                            0 );

        // Unable to read data or no data available
        if ( FAILED(hr) || dwElements == 0) 
        {
            break;
        }

        // look at the element to see what happened
        switch (od.dwOfs) 
        {     
            case DIMOFS_X:       // Mouse horizontal motion 
				x+=od.dwData; 
                break;

            case DIMOFS_Y:       // Mouse vertical motion 
                y+=od.dwData; 
                break;

        
            case DIMOFS_BUTTON0: // Right button pressed or released 
            case DIMOFS_BUTTON1: // Left button pressed or released 
	        break;
        }
    }
}